package org.jeecgframework.web.controller;
import java.io.File;
import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.CbsPartInfoServiceI;
import org.jeecgframework.web.service.impl.ImgCompressService;
import org.jeecgframework.web.system.pojo.base.CbsPartImageEntity;
import org.jeecgframework.web.system.pojo.base.CbsPartInfoEntity;
import org.jeecgframework.web.system.pojo.base.TSTypegroup;
import org.jeecgframework.web.system.pojo.base.ZyEquipmentSpareEntity;
import org.jeecgframework.web.system.pojo.base.ZyFileLogEntity;
import org.jeecgframework.web.system.pojo.base.ZyInspectionPlanEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.FileBean;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.UploadFileUtil;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;



/**   
 * @Title: Controller
 * @Description: 零件信息表
 * @author onlineGenerator
 * @date 2016-08-03 15:20:26
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsPartInfoController")
public class CbsPartInfoController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CbsPartInfoController.class);
	@Autowired
	private CbsPartInfoServiceI cbsPartInfoService;
	@Autowired
	private SystemService systemService;
	private String message;

    @Autowired
    private ImgCompressService imgCompressService;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 零件信息表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "cbsPartInfo")
	public ModelAndView cbsPartInfo(HttpServletRequest request) {
		
		return new ModelAndView("com/zybk/cbs_partinfo/cbsPartInfoList");
	}
	
	/**
	 * 零件信息表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "cbsPartInfoSelList")
	public ModelAndView cbsPartInfoSelList(HttpServletRequest request) {
        request.setAttribute("canSale", oConvertUtils.getString(request.getParameter("canSale")));
		return new ModelAndView("com/zybk/cbs_partinfo/cbsPartInfoSelList");
	}
    
	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(CbsPartInfoEntity cbsPartInfo,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(CbsPartInfoEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsPartInfo, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.cbsPartInfoService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 零件信息表新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(CbsPartInfoEntity cbsPartInfo, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(cbsPartInfo.getId())) {
			cbsPartInfo = cbsPartInfoService.getEntity(CbsPartInfoEntity.class, cbsPartInfo.getId());
			req.setAttribute("cbsPartInfoPage", cbsPartInfo);
		}	
		req.setAttribute("sessionId", req.getSession().getId());
		return new ModelAndView("com/zybk/cbs_partinfo/cbsPartInfo-add");
	}
	
	
	/**
	 * 添加文件
	 * @param request
	 * @return
	 */
	@RequestMapping(params="saveImgFiles")
	@ResponseBody
	public FileBean saveImgFiles(HttpServletRequest request){
		MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = req.getFile("Filedata");
		String suffix = multipartFile.getOriginalFilename().substring  
				(multipartFile.getOriginalFilename().lastIndexOf("."));     
		///**使用UUID生成文件名称**/    
		String filePath=StaticValue.UPLOAD_PATH;
		File temporaryFile = new File(filePath);
		if  (!temporaryFile.exists()  && !temporaryFile.isDirectory()){
			temporaryFile .mkdir();
		}
		String newFileName = UUID.randomUUID().toString()+ suffix;//构建文件名称     
		String fileRealName=multipartFile.getOriginalFilename();
		String uploadPath = filePath + newFileName;
		File file = new File(uploadPath);
		try {
			multipartFile.transferTo(file);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		FileBean f=new FileBean();
		f.setFileName(newFileName);
		f.setFilePath(uploadPath);
		f.setFileRealName(fileRealName);
        imgCompressService.startCompress(f);
		return f;
	}
	
	
	@RequestMapping(params="getPartInfoByPartNo")
	@ResponseBody
	public Map<String, Object> getPartInfoByPartNo(HttpServletRequest request,String param,String id){
		Map<String, Object> map = new HashMap<String, Object>();
		StringBuffer sb = new StringBuffer("from CbsPartInfoEntity where partNo = ? ");
		if(StringUtil.isNotEmpty(id)){
			sb.append(" and id <> '"+id+"'");
		}
		List<CbsPartInfoEntity> info = systemService.findHql(sb.toString(), param);
		if(info.size() > 0){
			map.put("info", "零件号已存在");
			map.put("status", "n");
		}else{
			map.put("info", "验证通过");
			map.put("status", "y");
		}
		return map;
	}
	
	/**
	 * 下载文件
	 * @param request
	 * @param response
	 * @param filePath 全路径
	 */
	@ResponseBody
	@RequestMapping(params="downLoadFile")
	public void downLoadFile(HttpServletRequest request,HttpServletResponse response,String filePath){
		File file = new File(filePath);
		try {
			UploadFileUtil.downFile(request, response, new FileBean(file.getPath(),file.getName()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

	/**
	 * 添加零件信息表
	 * 
	 * @param typeCodeStr
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(CbsPartInfoEntity cbsPartInfo, 
			HttpServletRequest request,
			String typeCodeStr,String priceStr,String filePathStr,String fileNameStr,String fileRealNameStr) {
		AjaxJson j = new AjaxJson();
        if(StringUtil.isEmpty(cbsPartInfo.getCanSale())){
            /*默认可售*/
            cbsPartInfo.setCanSale("1");
        }
		message = "零件信息添加成功";
		try{
            if(cbsPartInfo != null && cbsPartInfo.getWechatPrice() == 0){
                cbsPartInfo.setWechatPrice(cbsPartInfo.getTerminalPrice());
            }
			cbsPartInfoService.save(cbsPartInfo);
			if(StringUtil.isNotEmpty(filePathStr)){
				String filePaths [] = filePathStr.split(",");
				String fileNames [] = fileNameStr.split(",");
				String fileRealNames [] = fileRealNameStr.split(",");
				List<CbsPartImageEntity> imgList = new ArrayList<CbsPartImageEntity>();
				for (int i = 0; i < filePaths.length; i++) {
					CbsPartImageEntity img = new CbsPartImageEntity();
					img.setAllPath(filePaths[i]);
					img.setFilename(fileNames[i]);
					img.setFilerealname(fileRealNames[i]);
					img.setIsColumnimage("0");
					img.setPartId(cbsPartInfo.getId());
					imgList.add(img);
				}
				systemService.batchSave(imgList);
			}
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "零件信息添加失败";
		}
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 零件信息表编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(HttpServletRequest req,String id ) {
		CbsPartInfoEntity info = systemService.get(CbsPartInfoEntity.class, id);		
//		req.setAttribute("CbsPartPricePage", info.getCbsPartPrice());
		req.setAttribute("cbsPartInfoPage", info);
//		TSTypegroup typeGroup = systemService.getTypeGroupByCode("partsPrice");
//		req.setAttribute("type", typeGroup.getTSTypes());
		req.setAttribute("sessionId", req.getSession().getId());
		return new ModelAndView("com/zybk/cbs_partinfo/cbsPartInfo-update");
	}
	/**
	 * 零件信息表编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate1")
	public ModelAndView goUpdate1(HttpServletRequest req,String id ) {
		CbsPartInfoEntity info = systemService.get(CbsPartInfoEntity.class, id);		
//		req.setAttribute("CbsPartPricePage", info.getCbsPartPrice());
		req.setAttribute("cbsPartInfoPage", info);
//		TSTypegroup typeGroup = systemService.getTypeGroupByCode("partsPrice");
//		req.setAttribute("type", typeGroup.getTSTypes());
		req.setAttribute("sessionId", req.getSession().getId());
		return new ModelAndView("com/zybk/cbs_partinfo/editPartInfo1");
	}
	/**
	 * 零件信息表编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate2")
	public ModelAndView goUpdate2(HttpServletRequest req,String id ) {
		CbsPartInfoEntity info = systemService.get(CbsPartInfoEntity.class, id);		
//		req.setAttribute("CbsPartPricePage", info.getCbsPartPrice());
		req.setAttribute("cbsPartInfoPage", info);
//		TSTypegroup typeGroup = systemService.getTypeGroupByCode("partsPrice");
//		req.setAttribute("type", typeGroup.getTSTypes());
		req.setAttribute("sessionId", req.getSession().getId());
		return new ModelAndView("com/zybk/cbs_partinfo/editPartInfo2");
	}
	
	/**
	 * 更新零件信息表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(CbsPartInfoEntity cbsPartInfo, 
			HttpServletRequest request,
			String typeCodeStr,String priceStr,String filePathStr,String fileNameStr,String fileRealNameStr) {
		AjaxJson j = new AjaxJson();
		message = "零件信息更新成功";
        if(cbsPartInfo != null && cbsPartInfo.getWechatPrice() == 0){
            cbsPartInfo.setWechatPrice(cbsPartInfo.getTerminalPrice());
        }
		CbsPartInfoEntity t = cbsPartInfoService.get(CbsPartInfoEntity.class, cbsPartInfo.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(cbsPartInfo, t);
			if(StringUtil.isNotEmpty(filePathStr)){
				String filePaths [] = filePathStr.split(",");
				String fileNames [] = fileNameStr.split(",");
				String fileRealNames [] = fileRealNameStr.split(",");
				systemService.deleteAllEntitie(t.getPartImgList());
				List<CbsPartImageEntity> imgList = new ArrayList<CbsPartImageEntity>();
					for (int i = 0; i < filePaths.length; i++) {
						CbsPartImageEntity img = new CbsPartImageEntity();
						img.setAllPath(filePaths[i]);
						img.setFilename(fileNames[i]);
						img.setFilerealname(fileRealNames[i]);
						img.setIsColumnimage("0");
						img.setPartId(t.getId());
						imgList.add(img);
					}
				systemService.batchSave(imgList);
			}
			cbsPartInfoService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "零件信息更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 根据零件id 查询零件信息
	 * @param id
	 * @return
	 */
	@RequestMapping(params="getPartInfoById")
	@ResponseBody
	public List<Map<String,Object>> getPartInfoById(String id){
		List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
		id = id.replace(",", "','");
		List<CbsPartInfoEntity> infoList = systemService.findHql("from CbsPartInfoEntity where id in('"+id+"')");
		for (CbsPartInfoEntity info : infoList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", info.getId());
			map.put("no", info.getPartNo());
			map.put("chineseDes", info.getChineseDes());
			map.put("unit", systemService.getTypeByCode(StaticValue.DIC_MARKET_UNIT, info.getMarketUnit()));
			dataList.add(map);
		}
		return dataList;
	}
	
	/**
	 * 根据设备id查询设备
	 * @param id 设备id
	 * @return
	 */
	@RequestMapping(params="getEquipmentIdById")
	@ResponseBody
	public List<Map<String,Object>> getEquipmentIdById(String id){
		List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
		id = id.replace(",", "','");
		List<ZyEquipmentSpareEntity> equipmentList = systemService.findHql("from ZyEquipmentSpareEntity where id in('"+id+"')");
		
		for (ZyEquipmentSpareEntity info : equipmentList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", info.getId());
			map.put("sn", info.getSn());
			map.put("item", info.getItem());
            if(info.getType() != null){
                map.put("type", info.getType().getTypeDesc());
            }
            if(info.getHouse() != null){
                map.put("room", info.getHouse().getRoomNum());
            }
			map.put("BP", StringUtil.isNotEmpty(info.getTsDepart().getBpCode())?info.getTsDepart().getBpCode():"");
			map.put("installDate",StringUtil.isNotEmpty(info.getInstallDate())?DataUtils.formatDate(info.getInstallDate(), "yyyy-MM-dd"):"");
			map.put("repairEndDate",StringUtil.isNotEmpty(info.getRepairEndDate())?DataUtils.formatDate(info.getRepairEndDate(), "yyyy-MM-dd"):"");
            String isInRepairDate = "0";
            if(info.getRepairEndDate().after(new Date())){
                isInRepairDate = "1";
            }else if(info.getRepairEndDate().before(new Date())){
                isInRepairDate = "2";
            }
            map.put("isInRepair",isInRepairDate);
            //0.无巡检计划 1.本年度已巡检 2.有巡检计划
			map.put("inspectionType", 0);
			List<ZyInspectionPlanEntity> inspectionPlanList = systemService.findHql("from ZyInspectionPlanEntity where equipmentSpare.id = ? and year(ipPlanDate) = ? order by ipPlanDate desc",info.getId(),DataUtils.getYear());
			if(inspectionPlanList.size() > 0){
				if(StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE.equals(inspectionPlanList.get(0).getState())){
					map.put("inspectionType", 1);
				}else if(!StaticValue.DIC_PLAN_STATE_INSPECTION_CANCEL.equals(inspectionPlanList.get(0).getState())){
                    map.put("inspectionType", 2);
                }
			}
			
			dataList.add(map);
		}
        Collections.sort(dataList, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                String o1InRepair = oConvertUtils.getString(o1.get("isInRepair"));
                String o2InRepair = oConvertUtils.getString(o2.get("isInRepair"));
                if(oConvertUtils.getInt(o2InRepair) != oConvertUtils.getInt(o1InRepair)){
                    return 1;
                }else{
                    String o1inspectionType = oConvertUtils.getString(o1.get("inspectionType"));
                    String o2inspectionType = oConvertUtils.getString(o2.get("inspectionType"));
                    return oConvertUtils.getInt(o1inspectionType) - oConvertUtils.getInt(o2inspectionType);
                }
            }
        });
		return dataList;
	}
	
	

	
	/**
	 * 删除零件信息表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(CbsPartInfoEntity cbsPartInfo, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		cbsPartInfo = systemService.getEntity(CbsPartInfoEntity.class, cbsPartInfo.getId());
		message = "零件信息表删除成功";
		try{
			cbsPartInfoService.delete(cbsPartInfo);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "零件信息表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除零件信息表
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		message = "零件信息表删除成功";
		try{
			for(String id:ids.split(",")){
				CbsPartInfoEntity cbsPartInfo = systemService.getEntity(CbsPartInfoEntity.class, 
				id
				);
				cbsPartInfoService.delete(cbsPartInfo);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "零件信息表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		return new ModelAndView("com/zybk/cbs_partinfo/cbsPartInfoUpload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(CbsPartInfoEntity cbsPartInfo,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(CbsPartInfoEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsPartInfo, request.getParameterMap());
		List<CbsPartInfoEntity> cbsPartInfos = this.cbsPartInfoService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"零件信息表");
		modelMap.put(NormalExcelConstants.CLASS,CbsPartInfoEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("零件信息表列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,cbsPartInfos);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(CbsPartInfoEntity cbsPartInfo,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		modelMap.put(TemplateExcelConstants.FILE_NAME, "零件信息表");
		modelMap.put(TemplateExcelConstants.PARAMS,new TemplateExportParams("Excel模板地址"));
		modelMap.put(TemplateExcelConstants.MAP_DATA,null);
		modelMap.put(TemplateExcelConstants.CLASS,CbsPartInfoEntity.class);
		modelMap.put(TemplateExcelConstants.LIST_DATA,null);
		return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<CbsPartInfoEntity> listCbsPartInfoEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(),CbsPartInfoEntity.class,params);
				for (CbsPartInfoEntity cbsPartInfo : listCbsPartInfoEntitys) {
					cbsPartInfoService.save(cbsPartInfo);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
}
